<template>
	<div class="layout-flex">
		<!-- 头部tab 从字典中拿 -->
		<div class="tabHeader">
			<el-tabs v-model="state.activeName" class="header-tabs" @tab-change="handleChange">
				<el-tab-pane label="全部" name=""> </el-tab-pane>
				<el-tab-pane v-for="tab in state.headerTabsList" :key="tab.value" :label="tab.label" :name="tab.value"></el-tab-pane>
			</el-tabs>
		</div>
		<!-- 头部搜索条件 -->
		<FastFilter @search="toRefresh" @reset="resetList">
			<template v-slot:leftFilters>
				<CompanySelect @change="handleSearch($event, 'companyIds')" v-model="state.queryForm.companyIds" class="w180" :teamRef="teamSelectRef" />
				<TeamSelect @change="handleSearch($event, 'teamIds')" v-model="state.queryForm.teamIds" class="w180" ref="teamSelectRef" />
				<StockAreaSelect @change="handleSearch($event, 'stockupAreaCodes')" v-model="state.queryForm.stockupAreaCodes" class="w180" />
				<StockPlatformSelect @change="handleSearch($event, 'stockupPlatformCodes')" v-model="state.queryForm.stockupPlatformCodes" class="w180" />
				<WareSelect @change="handleSearch($event, 'whIdFroms')" v-model="state.queryForm.whIdFroms" title="发货仓库" class="w180" />
				<StoreListSelect @change="handleSearch($event, 'storeIdList')" title="店铺" v-model="state.queryForm.storeIdList" class="w180" />

				<!-- 业务类型 -->
				<FunctionalSelect
					v-model="state.queryForm.busTypeList"
					:optionFormat="{
						key: 'value',
						label: 'label',
					}"
					useRadio
					:options="state.busTypeList"
					placeholder="业务类型"
					@query-list="handleSearch($event, 'busTypeList')"
					class="w180"
				/>
				<!-- 单据状态 -->
				<FunctionalSelect
					v-if="state.activeName === '' || state.activeName === '1,3'"
					v-model="state.queryForm.statusCodeList"
					:optionFormat="{
						key: 'value',
						label: 'label',
					}"
					useRadio
					:options="state.statusCodeList"
					placeholder="单据状态"
					@query-list="handleSearch($event, 'statusCodeList')"
					class="w180"
				/>
				<UserSelect @change="handleSearch($event, 'createBys')" v-model="state.queryForm.createBys" title="创建人" class="w180" />
				<ComboSearch
					:options="state.comboSearchOpt"
					:prefixSelect="'busCode'"
					@search="handleComboSearch($event, 'searchDto')"
					ref="comboSearchRef"
				/>
				<!-- 时间 -->
				<date-picker-with-prefix
					class="transfer-slip-date"
					:options="state.datePickerOptions"
					:width="150"
					@change="changeDataRange"
					ref="datePickerRef"
				/>
			</template>
			<template #result>
				<FilterTag
					v-for="(item, index) in FilterTagOption"
					:key="index"
					:show="item.key()"
					:label="item.label()"
					:value="item.value()"
					@close="closeTag(item.clear)"
				/>
			</template>
		</FastFilter>

		<div class="layout-padding">
			<FastTableHandle @queryTable="toRefresh(false)">
				<template v-slot:leftBtns>
					<el-button v-if="state.activeName === '' && getAuth('wms_outbound_add')" type="primary" @click="toAdd">添加出库单</el-button>
					<el-button
						v-if="(state.activeName === '' || state.activeName === '1,3') && getAuth('wms_outbound_submit')"
						:type="state.activeName === '1,3' ? 'primary' : ''"
						class="ml10"
						@click="toSubmitOutbound()"
					>
						确认提交
					</el-button>
					<!-- <el-button v-if="state.activeName === '4'" type="primary">拣货</el-button> -->
					<el-dropdown
						v-if="(state.activeName === '' || state.activeName === '5' || state.activeName === '6') && getAuth('wms_outbound_view')"
						class="ml10"
					>
						<el-button>
							打印操作
							<el-icon>
								<arrow-down />
							</el-icon>
						</el-button>
						<template #dropdown>
							<el-dropdown-menu>
								<el-dropdown-item command="1" v-if="state.activeName !== '6'" @click="toPrint">打印拣货清单</el-dropdown-item>
								<el-dropdown-item command="2" v-if="state.activeName === ''">打印FNSKU条码</el-dropdown-item>
								<el-dropdown-item command="2" v-if="state.activeName !== '5'" @click="toPreviewFile">打印箱唛</el-dropdown-item>
								<!-- <el-dropdown-item command="2" v-if="state.activeName !== ''">打印出库单</el-dropdown-item> -->
							</el-dropdown-menu>
						</template>
					</el-dropdown>
					<el-button type="" v-if="(state.activeName === '' || state.activeName === '4') && getAuth('wms_outbound_pick')" @click="toBatchPick()"
						>完成拣货</el-button
					>
					<el-button
						:type="state.activeName === '5' ? 'primary' : ''"
						v-if="(state.activeName === '' || state.activeName === '5') && getAuth('wms_outbound_packed')"
						class="ml10"
						@click="toBatchCompletePack()"
					>
						完成装箱
					</el-button>
					<el-button
						v-if="(state.activeName === '' || state.activeName === '6') && getAuth('wms_outbound_out')"
						class="ml10"
						:type="state.activeName === '6' ? 'primary' : ''"
						@click="toBatchOutbound()"
						>确认出库</el-button
					>
					<span
						v-if="state.activeName !== '7' && state.activeName !== '8' && state.activeName !== '2' && state.checkedRows.length > 0"
						style="color: #a6abb4"
						class="ml10"
					>
						已选 <span style="color: #005bf5"> {{ state.checkedRows.length }} </span>条记录
					</span>
				</template>
				<template v-slot:rightWrapper>
					<el-icon style="cursor: pointer" @click="toExport" v-if="getAuth('wms_outbound_export')">
						<Download />
					</el-icon>
					<el-icon style="cursor: pointer" @click="columnsSettingRef.openDialog()">
						<Setting />
					</el-icon>
				</template>
			</FastTableHandle>

			<div class="layout-flex">
				<table-layout
					row-key="id"
					:queryForm="state.queryForm"
					:fetch-list="outboundPage"
					:span-method="arraySpanMethod"
					ref="dataTableRef"
					size="small"
					:row-class-name="tableRowClassName"
					:tree-props="{ children: 'items' }"
					:default-expand-all="true"
					@selection-change="handleSelectionChange"
					@mouseEnterCell="(row) => (rowIdx = row.id)"
					@mouseLeaveCell="rowIdx = null"
				>
					<template v-slot:tableLayout>
						<!-- <el-table-column label="" width="30px" fixed="left" /> -->
						<el-table-column :selectable="selectable" type="selection" fixed="left">
							<template v-slot="scope">
								<div v-if="!scope.row.items"></div>
							</template>
						</el-table-column>
						<el-table-column
							v-for="(col, ind) in columnsData.outDelList"
							:key="ind"
							:label="col.name"
							:prop="col.prop"
							:fixed="col.fixed ? col.fixed : false"
							:min-width="col.width ? col.width : '140'"
							:sortable="col.sortable"
						>
							<!-- th header -->
							<template #header>
								<div v-if="col.tooltip" style="display: flex; align-items: center">
									{{ col.name }}
									<el-tooltip effect="dark" :content="col.tooltip" placement="top">
										<el-icon><InfoFilled /></el-icon>
									</el-tooltip>
								</div>
								<span v-else>{{ col.name }}</span>
							</template>
							<template v-slot="scope">
								<div v-if="scope.row.items && (ind === 0 || col.fixed)" class="main-tc">
									<div v-for="it in columnsData.mainInfo" :key="it.prop" style="padding: 4px">
										<template v-if="it.checked">
											<template v-if="it.name === '出库单号'">
												<el-link type="primary" @click="toDetail(scope.row)">{{ scope.row[it.prop] }}</el-link>
												<span @click="() => copyText(scope.row[it.prop])">
													<el-icon class="text-xs cursor-pointer" v-if="rowIdx === scope.row.id">
														<DocumentCopy />
													</el-icon>
												</span>
											</template>
											<el-tag v-else-if="it.name === '单据状态'" :type="tagTypes[scope.row[it.prop]]" effect="plain">
												<span v-for="item in state.outDelOrderStatus" :key="item.id" v-show="Number(item.value) === scope.row.statusCode">
													{{ item.label }}
												</span>
											</el-tag>
											<div v-else-if="it.name === '业务类型'">
												{{ it.name }}：
												<span v-for="item in state.busTypeList" :key="item.id" v-show="Number(item.value) === Number(scope.row[it.prop])">
													{{ item.label }}
												</span>
											</div>
											<div v-else-if="it.name === '店铺'">
												{{ it.name }}：
												{{ (scope.row.marketCode || '') + '_' + (scope.row.storeCode || '') }}
											</div>
											<div v-else-if="it.name === 'FBA货件号'">
												{{ it.name }}：
												<el-text type="primary">{{ scope.row[it.prop] }}</el-text>
											</div>
											<div v-else> {{ it.name }}：{{ scope.row[it.prop] }} </div>
										</template>
									</div>
								</div>
								<div v-else>
									<template v-if="col.name === 'MSKU / FNSKU'">
										<div>{{ scope.row.mskuCode || '--' }}</div>
										<div style="margin-top: 16px">{{ scope.row.fnsku || '--' }}</div>
									</template>
									<template v-else-if="col.name === '产品质量'">
										<div>{{ scope.row[col.prop] === '1' ? '良品' : scope.row[col.prop] === '2' ? '次品' : '' }}</div>
									</template>
									<template v-else-if="col.name === '拣货信息'">
										<el-text type="info" v-if="!scope.row[col.prop] || scope.row[col.prop]?.length === 0"> 尚未拣货，未分配库位 </el-text>
										<el-popover v-else placement="bottom" width="600px" trigger="click">
											<template #reference>
												<div class="cursor-pointer flex items-center">
													<div>
														已分配
														<el-text type="primary">{{ scope.row[col.prop]?.length }}</el-text>
														个库位
													</div>
													<el-icon><ArrowDown /></el-icon>
												</div>
											</template>
											<el-table :data="scope.row.pickList">
												<el-table-column width="190" prop="skuCode" label="SKU">
													<template #default="{ row }">
														{{ row.skuCode }}
														<el-tag type="warning" v-if="row.skuType === '4'">辅</el-tag>
													</template>
												</el-table-column>
												<el-table-column width="160" prop="batchCode" label="批次" />
												<el-table-column width="120" prop="positionCode" label="库位" />
												<el-table-column width="100" prop="pickQty" label="拣货数量">
													<template #default="{ row }">
														<el-text type="danger">{{ row.pickQty }}</el-text>
													</template>
												</el-table-column>
											</el-table>
										</el-popover>
									</template>
									<template v-else-if="col.name === 'SKU'">
										<div>
											{{ scope.row.skuCode || '--' }}
											<span v-if="scope.row.skuCode" @click="() => copyText(scope.row.skuCode)">
												<el-icon class="text-xs cursor-pointer" v-if="rowIdx === scope.row.id">
													<DocumentCopy />
												</el-icon>
											</span>
										</div>
									</template>
									<template v-else-if="col.name === '产品名称 / 属性'">
										<div>
											{{ scope.row.skuName || '--' }}
											<span v-if="scope.row.skuName" @click="() => copyText(scope.row.skuName)">
												<el-icon class="text-xs cursor-pointer" v-if="rowIdx === scope.row.id">
													<DocumentCopy />
												</el-icon>
											</span>
										</div>
										<!-- <div style="margin-top: 16px">{{ scope.row.skuAttrs || '--' }}</div> -->
										<div style="margin-top: 16px">
											<el-popover v-if="JSON.parse(scope.row.skuAttrs || 'null')" placement="bottom" trigger="click">
												<template #reference>
													<span style="cursor: pointer">
														{{ JSON.parse(scope.row.skuAttrs)[0]?.attrKeyName }} : {{ JSON.parse(scope.row.skuAttrs)[0]?.attrValue }}
														<el-icon><ArrowDown /></el-icon>
													</span>
												</template>
												<div v-for="(item, index) in JSON.parse(scope.row.skuAttrs)" :key="index">{{ item.attrKeyName }} : {{ item.attrValue }}</div>
											</el-popover>
											<!-- <span style="float: right; color: red">{{ scope.row.specialAttrs }}</span> -->

											<span v-if="scope.row.specialAttrs" style="float: right; color: red">
												<template v-for="(item, index) in scope.row.specialAttrs?.split(',')">
													<span v-for="it in prod_special_attr" :key="it" v-show="it.value === item"
														>{{ it.label }}{{ index === scope.row.specialAttrs?.split(',').length - 1 ? '' : '、' }}
													</span>
												</template>
											</span>
										</div>
									</template>
									<template v-else-if="col.name === '图片'">
										<div class="list-image">
											<ewt-image
												:url="scope.row[col.prop]"
												style="width: 36px; height: 36px; object-fit: contain; display: inline-block; cursor: pointer"
												@click="showImageViewer(scope.row[col.prop])"
											/>
											<div class="tag-combination" v-if="scope.row.skuType === '2'">组</div>
										</div>

										<!-- <div v-else class="non-pic">无图</div> -->
									</template>
									<template v-else>
										{{ scope.row[col.prop] }}
									</template>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="操作" width="180px" fixed="right">
							<template v-slot="scope">
								<div v-if="scope.row.items">
									<el-button type="primary" link @click="toDetail(scope.row)" v-if="getAuth('wms_outbound_view')"> 详情 </el-button>
									<el-dropdown>
										<el-button link type="primary">
											操作
											<el-icon class="el-icon--right">
												<arrow-down />
											</el-icon>
										</el-button>
										<template #dropdown>
											<el-dropdown-item
												v-if="(scope.row.statusCode === 1 || scope.row.statusCode === 3) && getAuth('wms_outbound_edit')"
												@click="toEdit(scope.row)"
											>
												编辑
											</el-dropdown-item>
											<el-dropdown-item v-if="scope.row.statusCode === 1 && getAuth('wms_outbound_submit')" @click="toSubmitOutbound(scope.row)"
												>确认提交</el-dropdown-item
											>
											<el-dropdown-item
												v-if="scope.row.statusCode !== 1 && scope.row.outboundType !== '1' && scope.row.flowFlag == '1'"
												@click="toApproval(scope.row)"
											>
												查看审批进度
											</el-dropdown-item>
											<el-dropdown-item
												v-if="scope.row.statusCode === 4 && getAuth('wms_outbound_pick')"
												@click="orderPickingDialogRef.openDialog(scope.row)"
											>
												拣货
											</el-dropdown-item>
											<el-dropdown-item
												v-if="(scope.row.statusCode === 5 || scope.row.statusCode === 6) && getAuth('wms_outbound_packed')"
												@click="encasementDialogRef.openDialog(scope.row)"
												>装箱</el-dropdown-item
											>
											<el-dropdown-item v-if="scope.row.statusCode === 6" @click="toBatchOutbound(scope.row)">出库</el-dropdown-item>
											<el-dropdown-item
												v-if="
													getAuth('wms_outbound_cancle') &&
													(((scope.row.statusCode === 1 || scope.row.statusCode === 3) && scope.row.outboundType === '0') ||
														scope.row.statusCode === 4 ||
														scope.row.statusCode === 5 ||
														(scope.row.statusCode === 6 && scope.row.outboundType === '1'))
												"
												@click="toCancelOutbound(scope.row)"
											>
												作废
											</el-dropdown-item>

											<!-- v-if="
													(scope.row.statusCode === 1 || scope.row.statusCode === 3) &&
													scope.row.outboundType === '0' &&
													getAuth('wms_outbound_cancle')
												" -->
										</template>
									</el-dropdown>
								</div>
							</template>
						</el-table-column>
					</template>
				</table-layout>
			</div>
		</div>
		<!-- 列设置 -->
		<ColumnsSetting
			ref="columnsSettingRef"
			@changeColumn="changeColumn"
			:allList="columns['outDelList']"
			:commitName="'outDelList'"
			:list="columnsData['outDelList']"
			:mainInfo="columnsData['mainInfo']"
		/>
		<orderPickingDialog ref="orderPickingDialogRef" @refresh="toRefresh" />
		<encasementDialog ref="encasementDialogRef" @refresh="toRefresh" />
		<printDialog ref="printDialogDialogRef" />
		<ewt-image-viewer v-if="state.imageViewer" :url-list="[state.imageViewer]" @close="closeViewer" />
	</div>
</template>
<script lang="ts" setup  name="outboundDeliveryOrder">
import { downBlobFile } from '/@/utils/other';
import { auth } from '/@/utils/authFunction';
const getAuth = (value: string) => {
	return auth(value);
};

import { ElMessage, ElMessageBox } from 'element-plus';
import { Local } from '/@/utils/storage';

const ColumnsSetting = defineAsyncComponent(() => import('./columnsSetting/index.vue'));
const printDialog = defineAsyncComponent(() => import('./printDialog.vue'));
import { columns } from './columnsSetting/columns.js';

import {
	getStoreList,
	outboundPage,
	submitOutbound,
	cancelOutbound,
	batchPick,
	batchCompletePack,
	exportOutbound,
	batchOutbound,
	getDicts,
} from './api.ts';
const orderPickingDialog = defineAsyncComponent(() => import('./forms/orderPickingDialog.vue'));
const encasementDialog = defineAsyncComponent(() => import('./forms/encasementDialog.vue'));
import { useDict } from '/@/hooks/dict';
const { prod_special_attr } = useDict('prod_special_attr');
const tagTypes = ['', 'info', '', 'danger', 'warning', 'warning', 'success', 'info', 'info'];

import CommonFunction from '/@/utils/commonFunction';
const { copyText } = CommonFunction();
const rowIdx = ref(null);
const obj = {
	descs: 'woo.createTimestamp',
	companyIds: [],
	teamIds: [],
	stockupAreaCodes: [],
	stockupPlatformCodes: [],
	whIdFroms: [],
	statusCodeList: [],
	storeIdList: [],
	busTypeList: [],
	createBys: [],
	searchDto: {
		searchFieldId: '',
		searchMode: '',
		searchValue: '',
		searchValueList: [],
	},
	createTimeStart: '',
	createTimeEnd: '',
	outTimeStart: '',
	outTimeEnd: '',
};
const router = useRouter();
const state = reactive({
	queryForm: Object.assign({}, obj),
	activeName: '',
	headerTabsList: [
		{ value: '1,3', label: '待提交' },
		{ value: '2', label: '审批中' },
		{ value: '4', label: '待拣货' },
		{ value: '5', label: '待装箱' },
		{ value: '6', label: '待出库' },
		{ value: '7', label: '已完成' },
		{ value: '8', label: '已作废' },
	],

	outDelOrderStatus: [],
	statusCodeList: [],

	datePickerOptions: [
		{ label: '创建日期', value: 1 },
		{ label: '出库日期', value: 2 },
	],
	busTypeList: [],
	comboSearchOpt: [
		{ label: '平台单号', key: 'platformOrderCode' },
		{ label: '来源单号', key: 'busCode' },
		{ label: '出库单号', key: 'outboundCode' },
		{ label: '产品名称', key: 'prodName' },
		{ label: 'SKU', key: 'sku' },
		{ label: 'FNSKU', key: 'fnsku' },
		// { label: '创建人', key: '7' },
	],
	checkedRows: [],
	imageViewer: '',
});
const datePickerRef = ref();
const comboSearchRef = ref();
const dataTableRef = ref();
const columnsSettingRef = ref();
const orderPickingDialogRef = ref();
const printDialogDialogRef = ref();
const encasementDialogRef = ref();

const teamSelectRef = ref();
const clearDto = () => {
	state.queryForm.searchDto = {};
	comboSearchRef.value?.resetFields();
};
const filterTags = reactive({
	companyIds: [],
	teamIds: [],
	stockupAreaCodes: [],
	stockupPlatformCodes: [],
	whIdFroms: [],
	createBys: [],
	storeIdList: [],
});
const FilterTagOption = [
	{
		key: () => state.queryForm.searchDto?.searchFieldId,
		label: () => state.comboSearchOpt.find((item) => item.key === state.queryForm.searchDto?.searchFieldId)?.label,
		value: () => state.queryForm.searchDto?.searchValueList,
		clear: clearDto,
	},
	{
		key: () => state.queryForm.createBys.length,
		label: () => '创建人',
		value: () => filterTags.createBys.map((item) => item.name),
		clear: () => {
			state.queryForm.createBys = [];
		},
	},
	{
		key: () => state.queryForm.busTypeList.length,
		label: () => '业务类型',
		value: () => state.busTypeList.filter((item) => state.queryForm.busTypeList.indexOf(item.value) !== -1).map((item) => item.label),
		clear: () => {
			state.queryForm.busTypeList = [];
		},
	},

	{
		key: () => state.queryForm.storeIdList.length,
		label: () => '店铺',
		value: () => filterTags.storeIdList.map((item) => item.storeName),
		clear: () => {
			state.queryForm.storeIdList = [];
		},
	},
	{
		key: () => state.queryForm.whIdFroms.length,
		label: () => '发货仓库',
		value: () => filterTags.whIdFroms.map((item) => item.nodeName),
		clear: () => {
			state.queryForm.whIdFroms = [];
		},
	},
	{
		key: () => state.queryForm.stockupPlatformCodes.length,
		label: () => '备货平台',
		value: () => filterTags.stockupPlatformCodes.map((item) => item.platformName),
		clear: () => {
			state.queryForm.stockupPlatformCodes = [];
		},
	},
	{
		key: () => state.queryForm.stockupAreaCodes.length,
		label: () => '备货区域',
		value: () => filterTags.stockupAreaCodes.map((item) => item.label),
		clear: () => {
			state.queryForm.stockupAreaCodes = [];
		},
	},
	{
		key: () => state.queryForm.teamIds.length,
		label: () => '团队',
		value: () => filterTags.teamIds.map((item) => item.name),
		clear: () => {
			state.queryForm.teamIds = [];
		},
	},
	{
		key: () => state.queryForm.companyIds.length,
		label: () => '公司主体',
		value: () => filterTags.companyIds.map((item) => item.name),
		clear: () => {
			state.queryForm.companyIds = [];
		},
	},
];
const closeTag = (claar) => {
	claar();
	toRefresh();
};

const selectable = (row) => {
	return true;
};
onMounted(() => {
	getDictsObj();
});
const toExport = () => {
	try {
		let ids = state.checkedRows.map((item) => {
			return item.id;
		});
		exportOutbound({ query: state.queryForm, ids: ids }).then(() => {
			ElMessage({
				message: '出库单下载成功，请至【下载中心】下载查看',
				type: 'success',
			});
		});
	} catch (res) {
		ElMessage({
			message: res.msg,
			type: 'error',
		});
	}
};
// 作废
const toCancelOutbound = (row) => {
	ElMessageBox({
		title: '作废',
		type: 'warning',
		confirmButtonText: '确认',
		showCancelButton: true,
		cancelButtonText: '取消',
		message: h('p', null, [
			h('span', null, '确定要作废'),
			h(
				'span',
				{
					style: {
						color: 'red',
						padding: '0 5px',
					},
				},
				row.outboundCode
			),
			h('span', null, '吗？'),
		]),
	}).then(async () => {
		cancelOutbound(row.id)
			.then(() => {
				ElMessage({
					message: '作废成功',
					type: 'success',
				});
				toRefresh();
			})
			.catch((res) => {
				ElMessage({
					message: res.msg,
					type: 'error',
				});
			});
	});
};
// 装箱
const toBatchCompletePack = () => {
	let data = [];
	state.checkedRows.forEach((item) => {
		if (item.statusCode === 5) {
			data.push(item.id);
		}
	});
	if (state.checkedRows.length === 0) {
		ElMessage({
			message: '请选择操作的数据',
			type: 'error',
		});
		return false;
	} else if (!data || data.length !== state.checkedRows.length) {
		ElMessage({
			message: '只有待装箱状态的出库单才可批量装箱',
			type: 'error',
		});
		return false;
	}
	batchCompletePack(data, true)
		.then(() => {
			ElMessage({
				message: '批量装箱成功',
				type: 'success',
			});
			toRefresh();
		})
		.catch((res) => {
			ElMessage({
				message: res.msg,
				type: 'error',
			});
		});
};
// 拣货
const toBatchPick = () => {
	let data = [];
	state.checkedRows.forEach((item) => {
		if (item.statusCode === 4) {
			data.push(item.id);
		}
	});
	if (state.checkedRows.length === 0) {
		ElMessage({
			message: '请选择操作的数据',
			type: 'error',
		});
		return false;
	} else if (!data || data.length !== state.checkedRows.length) {
		ElMessage({
			message: '只有待拣货状态的出库单才可批量拣货',
			type: 'error',
		});
		return false;
	}
	batchPick(data)
		.then(() => {
			ElMessage({
				message: '批量拣货成功',
				type: 'success',
			});
			toRefresh();
		})
		.catch((res) => {
			ElMessage({
				message: res.msg,
				type: 'error',
			});
		});
};
// 出库
const toBatchOutbound = (row) => {
	let data = [];
	if (!row) {
		state.checkedRows.forEach((item) => {
			if (item.statusCode === 6) {
				data.push(item.id);
			}
		});
		if (state.checkedRows.length === 0) {
			ElMessage({
				message: '请选择操作的数据',
				type: 'error',
			});
			return false;
		} else if (!data || data.length !== state.checkedRows.length) {
			ElMessage({
				message: '只有待出库状态的出库单才可批量出库',
				type: 'error',
			});
			return false;
		}
	} else {
		data = [row.id];
	}

	batchOutbound(data)
		.then(() => {
			ElMessage({
				message: '批量出库成功',
				type: 'success',
			});
			toRefresh();
		})
		.catch((res) => {
			ElMessage({
				message: res.msg,
				type: 'error',
			});
		});
};
// 提交
const toSubmitOutbound = (row) => {
	let data = [];
	if (!row) {
		state.checkedRows.forEach((item) => {
			if (item.statusCode === 1) {
				data.push(item.id);
			}
		});
		if (state.checkedRows.length === 0) {
			ElMessage({
				message: '请选择操作的数据',
				type: 'error',
			});
			return false;
		} else if (!data || data.length !== state.checkedRows.length) {
			ElMessage({
				message: '只有草稿状态的出库单才可批量拣货',
				type: 'error',
			});
			return false;
		}
	} else {
		data = [row.id];
	}

	submitOutbound(data)
		.then(() => {
			ElMessage({
				message: '批量提交成功',
				type: 'success',
			});
			toRefresh();
		})
		.catch((res) => {
			ElMessage({
				message: res.msg,
				type: 'error',
			});
		});
};

const handleChange = () => {
	if (state.activeName === '1,3') {
		state.statusCodeList = [];
		state.outDelOrderStatus.forEach((item) => {
			item.value = Number(item.value);
			if (item.value === 1 || item.value === 3) {
				state.statusCodeList.push(item);
			}
		});
	} else {
		state.statusCodeList = state.outDelOrderStatus;
	}
	state.queryForm.statusCodeList = state.activeName ? (state.activeName.indexOf(',') === -1 ? [Number(state.activeName)] : [1, 3]) : [];
	toRefresh();
};
const toRefresh = (v) => {
	dataTableRef.value?.refresh(v);
};
const resetList = () => {
	Object.keys(obj).forEach((i) => {
		state.queryForm[i] = obj[i];
	});
	comboSearchRef.value?.resetFields();
	datePickerRef.value?.resetFields();
	// toRefresh();
	handleChange();
};
const showImageViewer = (img) => {
	state.imageViewer = img;
};
const closeViewer = () => {
	state.imageViewer = '';
};

// 头部获取到的值
const handleSearch = (data, type) => {
	const { ids, list } = data;
	filterTags[type] = list;

	// 联动
	if (type == 'companyIds') {
		state.queryForm.teamIds = [];
	}
	toRefresh();
};
const handleComboSearch = (ids, type) => {
	state.queryForm[type] = {};
	const { key, like, value } = ids;
	state.queryForm[type].searchFieldId = key;
	state.queryForm[type].searchValue = like;
	state.queryForm[type].searchValueList = value;
	state.queryForm[type].searchMode = value.length ? 'mode_in' : 'mode_like';

	toRefresh();
};
const changeDataRange = (val: unknown, v2: string[]) => {
	if (val === 1) {
		state.queryForm.outTimeStart = '';
		state.queryForm.outTimeEnd = '';
		state.queryForm.createTimeStart = v2[0] ? v2[0] + ' 00:00:00' : '';
		state.queryForm.createTimeEnd = v2[1] ? v2[1] + ' 23:59:59' : '';
	} else {
		state.queryForm.outTimeStart = v2[0] ? v2[0] + ' 00:00:00' : '';
		state.queryForm.outTimeEnd = v2[1] ? v2[1] + ' 23:59:59' : '';
		state.queryForm.createTimeStart = '';
		state.queryForm.createTimeEnd = '';
	}
	toRefresh();
};

// 字典
const getDictsObj = async () => {
	const { data: data1 } = await getDicts('outbound_bus_type');
	state.busTypeList = data1;
	const { data } = await getDicts('outbound_status');
	state.outDelOrderStatus = data;
	state.outDelOrderStatus.forEach((item) => {
		state.headerTabsList.forEach((it) => {
			if (it.value === item.value) {
				it.label = item.label;
			}
		});
	});
	handleChange();
};
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
	if (row.items) {
		let num = columnsData.outDelList.length >= 12 ? 12 : columnsData.outDelList.length;
		if (columnIndex === 1) {
			return [1, num];
		} else if (columnIndex > 1 && columnIndex < num + 1) {
			return [0, 0];
		} else {
			return [1, 1];
		}
	}
};
const tableRowClassName = ({ row, rowIndex }) => {
	if (row.items) {
		return 'rowHeader';
	}
	return '';
};
const handleSelectionChange = (val) => {
	state.checkedRows = val;
};
const columnsData = reactive({
	outDelList: Local.get('outDelList') || columns.outDelList,
	mainInfo: Local.get('mainInfo') || columns.mainInfo,
});

const changeColumn = (list, mainInfo) => {
	columnsData.outDelList = list;
	columnsData.mainInfo = mainInfo;
};
// 添加
const toAdd = () => {
	router.push({ path: '/warehouse/outboundDelivery/outboundDeliveryOrder/addOutDelivery', query: { tagsViewName: '新增出库单' } });
};
// 编辑
const toEdit = (row) => {
	router.push({ path: '/warehouse/outboundDelivery/outboundDeliveryOrder/addOutDelivery', query: { tagsViewName: '编辑出库单', id: row.id } });
};
// 详情
const toDetail = (row) => {
	router.push({ path: '/warehouse/outboundDelivery/outboundDeliveryOrder/detailInfo', query: { id: row.id } });
};
// 审批进度
const toApproval = (row) => {
	router.push({ path: '/warehouse/outboundDelivery/outboundDeliveryOrder/approvalProgress', query: { id: row.id } });
};
const toPreviewFile = () => {
	if (state.checkedRows.length !== 1 || state.checkedRows[0]?.statusCode !== 6) {
		ElMessage({
			message: '请选择一条待出库的出库单',
			type: 'error',
		});
	} else {
		// state.checkedRows[0].boxMarkUrl = '/admin/sys-file/ewayt/596fb6fa37794c04ae33fa46cae03fdb.pdf';
		if (state.checkedRows[0].boxMarkUrl) {
			let fileName = state.checkedRows[0].boxMarkUrl.substr(state.checkedRows[0].boxMarkUrl.lastIndexOf('/'));
			downBlobFile(state.checkedRows[0].boxMarkUrl, {}, fileName);
		} else {
			ElMessage({
				message: '此条出库单无箱唛信息',
				type: 'error',
			});
		}
	}
};
// 打印
const toPrint = () => {
	let arr = [5, 6, 7];
	if (state.checkedRows.length !== 1 || arr.indexOf(state.checkedRows[0]?.statusCode) === -1) {
		ElMessage({
			message: '请选择一条已拣货的出库单',
			type: 'error',
		});
		return false;
	}
	printDialogDialogRef?.value.openDialog(state.checkedRows[0].id);
};
</script>
<style scoped lang="scss" >
.tabHeader {
	padding: 0 20px 0 20px;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1px solid #efefef;
}
.header-tabs :deep(.el-tabs__header) {
	margin-bottom: 0;
}
// :deep(.el-table .row-header td) {
// 	background-color: #f5f7fa !important;
// }
.non-pic {
	background: rgba(11, 16, 25, 0.05);
	border: 1px solid rgba(0, 0, 0, 0.03);
	color: rgba(11, 16, 25, 0.12);
	border-radius: 2px;
	display: flex;
	-webkit-box-pack: center;
	-ms-flex-pack: center;
	justify-content: center;
	-webkit-box-align: center;
	-ms-flex-align: center;
	align-items: center;
	width: 36px;
	height: 36px;
	line-height: 36px;
	text-align: center;
}

:deep(.el-table [class*='el-table__row--level'] .el-table__expand-icon) {
	display: none;
}
.main-tc > div {
	width: 14%;
	display: inline-block;
}
</style>
